import * as React from 'react';
import { connect } from 'react-redux';
import { Form, Icon, Input, Button, Alert } from 'antd';
import './Index.scss';
import auth from 'components/common/auth';
import { Redirect } from 'react-router-dom';
import { fetchUserInfo } from 'actions/app';

const FormItem = Form.Item;

function getPrefixIcon(icon: string) {
  const props = {
    style: {
      fontSize: 13,
    },
  };

  return <Icon type={icon} {...props} />;
}

interface IndexProps {
  form: any;
  dispatch: any;
}
interface IndexState {
  errorMessage: any;
  inFlight: boolean;
  doRedirect: boolean;
}
class Index extends React.Component<IndexProps, IndexState> {
  static defaultProps: IndexProps = {
    form: {},
    dispatch: () => {},
  };
  constructor(props: IndexProps) {
    super(props);

    this.state = {
      errorMessage: null,
      inFlight: false,
      doRedirect: false,
    };
  }

  redirectToIndex = (result: any) => {
    const { dispatch } = this.props;

    dispatch(fetchUserInfo()).then((result: any) => {
      const { code, msg } = result.response;
      if (!code) {
        this.setState({
          doRedirect: true,
        });
      } else {
        this.setState({
          errorMessage: msg,
        });
      }
    });

    this.setState({
      inFlight: false,
    });
  };

  handleSubmitFail = (error: any) => {
    this.setState({
      errorMessage: error.message,
      inFlight: false,
    });
  };

  handleSubmit = (e: any) => {
    e.preventDefault();
    this.setState({
      errorMessage: null,
    });

    this.props.form.validateFields((err: any, values: Record<string, any>) => {
      if (!err) {
        this.setState({
          inFlight: true,
        });
        auth
          .login(values.mobile, values.password, values.nonce)
          .then(this.redirectToIndex)
          .catch(this.handleSubmitFail);
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { doRedirect, errorMessage, inFlight } = this.state;

    if (doRedirect) {
      return <Redirect to="/" />;
    }

    return (
      <div className="login-page">
        <div className="login-form-wrapper">
          <Form onSubmit={this.handleSubmit}>
            {errorMessage && (
              <Alert message={errorMessage} type="error" showIcon={true} className="error-alert" />
            )}
            <FormItem>
              {getFieldDecorator('mobile', {
                rules: [{ required: true, message: '请输入手机号！' }],
              })(<Input prefix={getPrefixIcon('user')} placeholder="手机号" />)}
            </FormItem>
            <FormItem>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码！' }],
              })(<Input prefix={getPrefixIcon('lock')} type="password" placeholder="密码" />)}
            </FormItem>
            <FormItem>
              {getFieldDecorator('nonce', {
                rules: [{ required: true, message: '请输入身份认证码！' }],
              })(<Input prefix={getPrefixIcon('solution')} type="text" placeholder="认证码" />)}
            </FormItem>

            <FormItem>
              <Button
                loading={inFlight}
                type="primary"
                htmlType="submit"
                className="login-form-button">
                登录
              </Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}

export default connect()(Form.create()(Index));
